package org.example.traing.WebSocket;


import org.example.traing.entity.ChatMessage;
import org.example.traing.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatHandler extends TextWebSocketHandler {

    @Autowired
     ChatService chatService;
    private static final Map<String, Map<String, WebSocketSession>> roomSessions = new ConcurrentHashMap<>();



    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String roomId = (String) session.getAttributes().get("roomId");
        roomSessions.putIfAbsent(roomId, new ConcurrentHashMap<>());
        roomSessions.get(roomId).put(session.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String roomId = (String) session.getAttributes().get("roomId");
        System.out.println("roomId:"+roomId);


        String payload = message.getPayload();
        System.out.println(payload);
        String[] parts = payload.split(":", 2);
        System.out.println(parts);
        String senderId = parts[0];
        String message_content = parts[1];

        ChatMessage chatMessage = new ChatMessage(roomId, senderId,message_content);
        System.out.println("session.getId():"+session.getId());
        System.out.println(message.getPayload());
        System.out.println("message revieice");
        chatService.saveMessage(chatMessage);

        for (WebSocketSession webSocketSession : roomSessions.get(roomId).values()) {
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(message);
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String roomId = (String) session.getAttributes().get("roomId");
        roomSessions.get(roomId).remove(session.getId());
        if (roomSessions.get(roomId).isEmpty()) {
            roomSessions.remove(roomId);
        }
    }
}
